//
//  DLInformationSearchVC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/12/13.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLInformationSearchVC.h"
#import "DLSearchView.h"
#import "DLInfoSearchTC.h"
#import "DLInfoSearchModel.h"

@interface DLInformationSearchVC ()

@property (nonatomic, strong) UIView *falseNavView;
@property (nonatomic, strong) DLSearchView *searchView;

@property (nonatomic, strong) NSMutableArray *searchDataSource;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, copy) NSString *searchKeyword;

@end

@implementation DLInformationSearchVC


- (void) setUpNav {
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem new];
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.translucent = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.pageNum = 1;
    self.searchDataSource = [NSMutableArray array];
    
    [self layoutSobControls];
    
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DLInfoSearchTC *istc = [tableView dequeueReusableCellWithIdentifier:@"DLInfoSearchTC"];
    DLInfoSearchModel *model = self.searchDataSource[indexPath.row];
    istc.searchModel = model;
    return istc;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchDataSource.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self searchViewEndEditing];
    
    DLInfoSearchModel *model = self.searchDataSource[indexPath.row];
    
    DLNormalWebVC *bvc = [DLNormalWebVC new];
    bvc.urlString = HTTPInfoDetail;
    bvc.newsId = model.infoId;
    bvc.titleString = @"详情";
    bvc.webViewType = DLWebViewType_InfoDetail;
    [kuserManager.lastVc.navigationController pushViewController:bvc animated:YES];
    
}
- (void) layoutSobControls {
    
    UIView *falseNavView = [UIView new];
    falseNavView.frame = CGRectMake(0, 0, kScreenWidth, kHeightNavigation);
    falseNavView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"normal_navbg"]];
    [self.view addSubview:falseNavView];
    self.falseNavView = falseNavView;
    
    DLSearchView *searchView = [[DLSearchView alloc] initWithFrame:CGRectMake(20, kHeightNavigationStatusBar + (44 - 30) / 2, kScreenWidth - 40 - 30, 30)];
    [falseNavView addSubview:searchView];
    [searchView.searchTF becomeFirstResponder];
    self.searchView = searchView;
    
    searchView.searchBlock = ^(NSString * _Nonnull keyWord) {
        self.searchKeyword = keyWord;
        [self searchInfoWithKeyword];
    };
    
    
    UIButton *cancelButton = [UIButton buttonWithType:0];
    cancelButton.frame = CGRectMake(searchView.right + 5, searchView.top, 40, searchView.height);
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = kBoldFont(14);
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [falseNavView addSubview:cancelButton];
    [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.plainTableView.frame = CGRectMake(0, self.falseNavView.bottom, kScreenWidth, kScreenSafeAreaHeight - self.falseNavView.height);
    [self.view addSubview:self.plainTableView];
    self.plainTableView.backgroundColor = [UIColor whiteColor];
    self.plainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.plainTableView registerClass:[DLInfoSearchTC class] forCellReuseIdentifier:@"DLInfoSearchTC"];
    
    self.plainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.pageNum=1;
        [self reloadNewData];
    }];
    
    self.plainTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.pageNum++;
        [self loadMoreData];
    }];
}
- (void) reloadNewData {
    [self searchInfoWithKeyword];
}
- (void) loadMoreData {
    [self searchInfoWithKeyword];
}

- (void) searchInfoWithKeyword {
    
    NSString *uniqueId = [DLKeyChainManager readUUID];
    if (isEmpty(uniqueId)) {
        uniqueId = [DLKeyChainManager createUUID];
        [DLKeyChainManager saveUUID:uniqueId];
    }
    
    NSString *postUrl = HTTPSearchInformation;
    NSDictionary *postDic = @{
                              @"user_id" : kuserManager.isLogin?kuserManager.userInfoModel.userid:uniqueId,
                              @"text" : self.searchKeyword,
                              @"count" : @"10",
                              @"page" : @(self.pageNum),
                              @"startTag" : @"",
                              @"endTag" : @""
                              };
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.labelText = @"加载中···";
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        [hud hide:YES];
        if (kRequestSuccess(responseObject)) {
            NSArray *dataArr = responseObject[@"result"];
            if (dataArr.count > 0) {
                [self.searchView.searchTF resignFirstResponder];
                if (self.pageNum == 1) {
                    
                    [self.searchDataSource removeAllObjects];
                }
                for (NSDictionary *dataDic in dataArr) {
                    DLInfoSearchModel *model = [DLInfoSearchModel mj_objectWithKeyValues:dataDic];
                    model.keyword = self.searchKeyword;
                    [self.searchDataSource addObject:model];
                }
                
                
            } else {
                kShowRequestMsg(@"暂无数据");
                if (self.pageNum > 1) {
                    self.pageNum--;
                }
            }
        } else {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            if (self.pageNum > 1) {
                self.pageNum--;
            }
        }
        [self.plainTableView reloadData];
        [self endAllRefresh];
    } failure:^(NSError * _Nonnull error) {
        [hud hide:YES];
        NSLog(@"请求接口失败，错误是：%@", error);
        if (self.pageNum > 1) {
            self.pageNum--;
        }
        [self.plainTableView reloadData];
        [self endAllRefresh];
    }];
}
- (void) endAllRefresh {
    
    [self.plainTableView.mj_header endRefreshing];
    [self.plainTableView.mj_footer endRefreshing];
}
- (void) cancelButtonClick {
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void) scrollViewDidScroll:(UIScrollView *)scrollView {
    [self searchViewEndEditing];
}
- (void) searchViewEndEditing {
    [self.searchView endEditing:YES];
}
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self setUpNav];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
